<template>
  <!-- 预览结果 -->
  <!-- <div class="preview-result">
    结果: {{ evaluateCondition(cellStr, [obj, obj.name], ['row', 'val']) }}
  </div>
  {{ formData }} -->

  <ElRow style="width: 100%">
    <ElCol :span="4">
      <el-select v-model="formData.field" placeholder="请选择字段" @change="handleFieldChange">
        <el-option
          v-for="option in availableOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
          :disabled="option.disabled"
        />
      </el-select>
    </ElCol>

    <ElCol :span="4">
      <el-select
        v-model="formData.condType"
        placeholder="请选择条件类型"
        @change="handleConditionTypeChange"
      >
        <el-option
          v-for="option in conditionOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
    </ElCol>
    <ElCol :span="4">
      <el-input
        v-model="formData.condValue"
        placeholder="请输入条件值"
        @input="handleConditionValueChange"
      />
    </ElCol>
    <ElCol :span="4">
      <slot name="condition-success" :value="formData" @update:value="handleConditionSuccessChange">
        <el-input
          v-model="formData.success"
          placeholder="请输入条件达成时显示的内容"
          @input="handleConditionSuccessChange"
        />
      </slot>
    </ElCol>
    <ElCol :span="4">
      <slot name="condition-fail" :value="formData" @update:value="handleConditionFailChange">
        <el-input
          v-model="formData.fail"
          placeholder="请输入条件未达成时显示的内容"
          @input="handleConditionFailChange"
        />
      </slot>
    </ElCol>
    <ElCol :span="4">
      <div class="value-display">{{ cellStr }}</div>
    </ElCol>
  </ElRow>
</template>

<script setup lang="ts">
import { computed, watch, ref } from 'vue'

// 类型定义
interface FormData {
  field: string
  condType: string
  condValue: string
  success: string
  fail: string
}

interface ConditionOption {
  label: string
  value: string
}

interface FieldOption {
  label: string
  value: string
  disabled?: boolean
}

// 示例数据对象
const obj = { name: '张三', age: 18 }

// /**
//  * 动态执行条件表达式
//  * @param condition 条件表达式
//  * @param data 数据数组
//  * @param paramNames 参数名称数组
//  * @returns 执行结果
//  */
// const evaluateCondition = (
//   condition: string,
//   data: unknown[],
//   paramNames: string[] = ['row'],
// ): unknown => {
//   if (!condition) return
//   const conditionStr = condition.indexOf('return') === -1 ? `return ${condition}` : condition
//   const func = new Function(paramNames.join(', '), conditionStr)
//   return func(...data)
// }

/**
 * 可用的字段选项
 */
const availableOptions = computed<FieldOption[]>(() => {
  const baseObjFields = Object.keys(obj).map((field) => `row.${field}`)
  const advancedFields = [
    { name: 'val', remark: '当前单元格值', disabled: false },
    { name: 'row', remark: '当前行数据', disabled: true },
  ]

  return [
    ...advancedFields.map((field) => ({
      label: field.remark ? `${field.name} (${field.remark})` : field.name,
      value: field.name,
      disabled: field.disabled,
    })),
    ...baseObjFields.map((field) => ({
      label: field,
      value: field,
      disabled: false,
    })),
  ]
})

/**
 * 条件类型选项
 */
const conditionOptions: ConditionOption[] = [
  { label: '等于', value: '==' },
  { label: '不等于', value: '!=' },
  { label: '大于', value: '>' },
  { label: '小于', value: '<' },
  { label: '大于等于', value: '>=' },
  { label: '小于等于', value: '<=' },
]

// Props 定义
const props = defineProps<{
  modelValue: string
}>()

// Emits 定义
const emits = defineEmits(['update:modelValue'])

// 计算属性：用于 v-model 双向绑定
const cellStr = computed({
  get: () => props.modelValue,
  set: (value) => emits('update:modelValue', value),
})

// 表单数据
const formData = ref<FormData>({
  field: '',
  condType: '',
  condValue: '',
  success: '123',
  fail: '',
})

/**
 * 解析条件表达式
 * @param condition 条件表达式字符串
 * @returns 解析后的条件对象
 */
const parseCondition = (condition: string) => {
  if (!condition) return

  const [conditionPart, resultPart] = condition.split('?')
  if (!conditionPart) return

  const operators = conditionOptions.map((opt) => opt.value)
  const operatorPattern = new RegExp(
    `\\s*(${operators
      .map((op) => op.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
      .sort((a, b) => b.length - a.length)
      .join('|')})\\s*`,
  )

  const match = conditionPart.match(operatorPattern)
  if (!match) return

  const operator = match[1]
  const parts = conditionPart.split(
    new RegExp(`\\s*${operator.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*`),
  )

  if (parts.length !== 2) return

  const field = parts[0].trim()
  let value = parts[1].trim()

  // 处理带引号的值
  if (value.startsWith('"') && value.endsWith('"')) {
    value = value.slice(1, -1)
  }

  // 解析结果部分
  let conditionSuccess = ''
  let conditionFail = ''
  if (resultPart) {
    const [success, fail] = resultPart.split(':')
    if (success) {
      conditionSuccess = success.trim().replace(/^"|"$/g, '')
    }
    if (fail) {
      conditionFail = fail.trim().replace(/^"|"$/g, '')
    }
  }

  const result = {
    field,
    operator,
    value,
    conditionSuccess,
    conditionFail,
  }
  return result
}

/**
 * 初始化表单数据
 */
const initFormData = () => {
  const parsed = parseCondition(props.modelValue)
  if (parsed) {
    formData.value.field = parsed.field
    formData.value.condType = parsed.operator
    formData.value.condValue = parsed.value
    formData.value.success = parsed.conditionSuccess
    formData.value.fail = parsed.conditionFail
  }
}

// 组件初始化
initFormData()

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newValue) => {
    const parsed = parseCondition(newValue)
    if (parsed) {
      formData.value.field = parsed.field
      formData.value.condType = parsed.operator
      formData.value.condValue = parsed.value
      formData.value.success = parsed.conditionSuccess
      formData.value.fail = parsed.conditionFail
    }
  },
)

/**
 * 更新条件表达式
 */
const updateCellStr = () => {
  const {
    field,
    condType: conditionType,
    condValue: conditionValue,
    success: conditionSuccess,
    fail: conditionFail,
  } = formData.value
  if (!field || !conditionType || !conditionValue) {
    cellStr.value = ''
    return
  }

  try {
    const isNumber = !isNaN(Number(conditionValue))
    const formattedValue = isNumber ? conditionValue : `"${conditionValue}"`
    let newCellStr = `${field} ${conditionType} ${formattedValue}`

    if (conditionSuccess || conditionFail) {
      newCellStr = `${newCellStr} ? "${conditionSuccess}" : "${conditionFail}"`
    }

    cellStr.value = newCellStr
  } catch (error) {
    console.error('表达式解析错误:', error)
    cellStr.value = '表达式格式错误'
  }
}

// 事件处理函数
const handleFieldChange = () => updateCellStr()
const handleConditionTypeChange = () => updateCellStr()
const handleConditionValueChange = () => updateCellStr()
const handleConditionSuccessChange = () => updateCellStr()
const handleConditionFailChange = () => updateCellStr()
</script>

<style scoped>
.el-col {
  padding-right: 10px;
}

.value-display {
  height: 100%;
  width: 100%;
  padding: 1px 11px;
  background-color: #f5f7fa;
  border-radius: 4px;
  box-sizing: border-box;
  border: var(--el-border-width) var(--el-border-style) var(--el-border-color);
}
</style>
